package com.doubao.user.controller;

import com.doubao.common.result.Result;
import com.doubao.user.dto.MembershipDTO;
import com.doubao.user.dto.MembershipLevelDTO;
import com.doubao.user.dto.VipInfoDTO;
import com.doubao.user.entity.MembershipLevel;
import com.doubao.user.service.MembershipService;
import com.doubao.user.service.MembershipSubscriptionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 会员控制器
 */
@RestController
@RequestMapping("/user/membership")
@RequiredArgsConstructor
@Tag(name = "会员管理", description = "会员相关接口")
@Slf4j
public class MembershipController {

    private final MembershipService membershipService;
    private final MembershipSubscriptionService membershipSubscriptionService;

    @GetMapping("/levels")
    @Operation(summary = "获取会员等级列表", description = "获取所有可用的会员等级")
    public Result<List<MembershipLevel>> getAllLevels() {
        return membershipService.getAllLevels();
    }

    @GetMapping("/levels/{levelId}")
    @Operation(summary = "获取会员等级详情", description = "根据ID获取会员等级详情")
    public Result<MembershipLevel> getLevelById(@PathVariable Integer levelId) {
        return membershipService.getLevelById(levelId);
    }

    /**
     * 新增方法 - 符合微信支付服务调用的路径
     * 获取会员等级详情
     *
     * @param levelId 会员等级ID
     * @return 会员等级DTO
     */
    @GetMapping("/level/{levelId}")
    @Operation(summary = "获取会员等级详情", description = "根据ID获取会员等级详情")
    public Result<MembershipLevelDTO> getMembershipLevelInfo(@PathVariable("levelId") Long levelId) {
        log.info("获取会员等级详情: levelId={}", levelId);
        try {
            Result<MembershipLevel> levelResult = membershipService.getLevelById(levelId.intValue());
            if (!levelResult.isSuccess()) {
                return Result.failed(levelResult.getMessage());
            }

            MembershipLevel level = levelResult.getData();
            MembershipLevelDTO dto = new MembershipLevelDTO();
            BeanUtils.copyProperties(level, dto);

            return Result.success(dto);
        } catch (Exception e) {
            log.error("获取会员等级详情异常: levelId={}", levelId, e);
            return Result.failed("系统繁忙，请稍后再试");
        }
    }

    @GetMapping("/info")
    @Operation(summary = "获取当前用户会员信息", description = "获取当前登录用户的会员详情")
    public Result<MembershipDTO> getUserMembership(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        return membershipService.getUserMembership(userId);
    }

    @PostMapping("/refresh")
    @Operation(summary = "刷新会员token", description = "刷新会员每日token")
    public Result<Void> refreshDailyTokens(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        return membershipService.refreshDailyTokens(userId);
    }

    @GetMapping("/chat/remaining")
    @Operation(summary = "获取剩余聊天次数", description = "获取当前登录用户的剩余聊天次数")
    public Result<Integer> getRemainingChatCount(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        int count = membershipService.getRemainingChatCount(userId);
        return Result.success(count);
    }

    @GetMapping("/switch/remaining")
    @Operation(summary = "获取剩余切换智能体次数", description = "获取当前登录用户的剩余切换智能体次数")
    public Result<Integer> getRemainingSwitchCount(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        int count = membershipService.getRemainingSwitchCount(userId);
        return Result.success(count);
    }

    @PostMapping("/consume/chat")
    @Operation(summary = "消费聊天次数", description = "消费当前登录用户的聊天次数")
    public Result<Void> consumeChatCount(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        return membershipService.consumeChatCount(userId);
    }

    @PostMapping("/consume/switch")
    @Operation(summary = "消费切换智能体次数", description = "消费当前登录用户的切换智能体次数")
    public Result<Void> consumeSwitchCount(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        return membershipService.consumeSwitchCount(userId);
    }

    @PostMapping("/check/chat")
    @Operation(summary = "检查聊天次数", description = "检查当前登录用户的聊天次数是否充足")
    public Result<Boolean> checkChatCount(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        boolean result = membershipService.hasSufficientChatCount(userId);
        return Result.success(result);
    }

    @PostMapping("/check/switch")
    @Operation(summary = "检查切换智能体次数", description = "检查当前登录用户的切换智能体次数是否充足")
    public Result<Boolean> checkSwitchCount(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        if (userId == null) {
            return Result.failed("用户未登录");
        }
        boolean result = membershipService.hasSufficientSwitchCount(userId);
        return Result.success(result);
    }

    @GetMapping("/packages")
    @Operation(summary = "获取会员套餐", description = "获取所有会员等级套餐")
    public Result<List<MembershipLevel>> getMembershipPackages() {
        return membershipService.getAllLevels();
    }

    /**
     * 创建会员订阅订单 (已移至 MembershipSubscriptionController)
     */
    /*
    @PostMapping("/subscribe")
    @Operation(summary = "创建会员订阅订单", description = "创建会员订阅订单并返回支付参数")
    public Result<MembershipOrderDTO> createSubscriptionOrder(
            @RequestHeader(value = "X-User-ID", required = true) Long userId,
            @RequestParam("levelId") Integer levelId,
            @RequestParam("subscriptionType") String subscriptionType,
            @RequestParam("clientIp") String clientIp) {
        
        log.info("创建会员订阅订单: userId={}, levelId={}, subscriptionType={}, clientIp={}",
                userId, levelId, subscriptionType, clientIp);
        
        try {
            return membershipSubscriptionService.createSubscriptionOrder(
                    userId, levelId, subscriptionType, clientIp);
        } catch (Exception e) {
            log.error("创建会员订阅订单异常", e);
            return Result.failed("创建会员订阅订单异常: " + e.getMessage());
        }
    }
    */

    /**
     * 查询会员订阅订单 (已移至 MembershipSubscriptionController)
     */
    /*
    @GetMapping("/order/{orderId}")
    @Operation(summary = "查询会员订阅订单", description = "查询会员订阅订单状态")
    public Result<MembershipOrderDTO> getSubscriptionOrder(
            @PathVariable("orderId") String orderId) {
        
        log.info("查询会员订阅订单: orderId={}", orderId);
        
        try {
            return membershipSubscriptionService.getSubscriptionOrder(orderId);
        } catch (Exception e) {
            log.error("查询会员订阅订单异常", e);
            return Result.failed("查询会员订阅订单异常: " + e.getMessage());
        }
    }
    */

    /**
     * 处理会员订阅支付成功 (建议移至 MembershipSubscriptionController)
     */
    /*
    @PostMapping("/payment-success/{orderId}")
    @Operation(summary = "处理会员订阅支付成功", description = "处理会员订阅支付成功，激活会员")
    public Result<Void> handlePaymentSuccess(
            @PathVariable("orderId") String orderId) {
        
        log.info("处理会员订阅支付成功: orderId={}", orderId);
        
        try {
            return membershipSubscriptionService.handleSubscriptionPaySuccess(orderId);
        } catch (Exception e) {
            log.error("处理会员订阅支付成功异常", e);
            return Result.failed("处理会员订阅支付成功异常: " + e.getMessage());
        }
    }
    */


    /**
     * 获取用户VIP信息（兼容旧接口路径）
     * 此方法映射到 /user/vip-info 路径，为了兼容前端已有的调用
     *
     * @param userId 用户ID
     * @return VIP信息
     */
    @GetMapping("/vip-info")
    @Operation(summary = "获取用户VIP信息", description = "获取当前用户的VIP会员信息（兼容接口）")
    public Result<VipInfoDTO> getUserVipInfo(@RequestHeader(value = "X-User-ID", required = false) Long userId) {
        log.info("获取用户VIP信息（兼容接口）: userId={}", userId);

        if (userId == null) {
            log.warn("用户未登录，无法获取VIP信息");
            return Result.failed("用户未登录");
        }

        try {
            // 调用会员服务获取会员信息
            Result<MembershipDTO> membershipResult = membershipService.getUserMembership(userId);

            if (!membershipResult.isSuccess()) {
                log.error("获取会员信息失败: {}", membershipResult.getMessage());
                return Result.failed(membershipResult.getMessage());
            }

            MembershipDTO membership = membershipResult.getData();

            // 转换为VipInfoDTO
            VipInfoDTO vipInfo = new VipInfoDTO();
            vipInfo.setUserId(userId);
            vipInfo.setIsVip(membership.getIsVip());
            vipInfo.setLevelId(membership.getLevelId());
            vipInfo.setLevelName(membership.getLevelName());
            vipInfo.setLevelCode(membership.getLevelCode());
            vipInfo.setSubscriptionType(membership.getSubscriptionType());
            vipInfo.setExpireTime(membership.getExpireTime());
            vipInfo.setDailyTokenLimit(membership.getDailyTokenLimit());
            vipInfo.setChatLimit(membership.getChatLimit());
            vipInfo.setSwitchAgentLimit(membership.getSwitchAgentLimit());
            vipInfo.setRemainingChatCount(membership.getRemainingChatCount());
            vipInfo.setRemainingSwitchCount(membership.getRemainingSwitchCount());

            // 设置订阅类型文本
            vipInfo.setSubscriptionTypeText(getSubscriptionTypeText(membership.getSubscriptionType()));

            // 计算剩余天数
            if (membership.getExpireTime() != null) {
                LocalDateTime now = LocalDateTime.now();
                long remainingDays = ChronoUnit.DAYS.between(now, membership.getExpireTime());
                vipInfo.setRemainingDays(remainingDays > 0 ? remainingDays : 0);
            }

            log.info("获取VIP信息成功: userId={}, isVip={}, levelName={}, subscriptionType={}",
                    userId, vipInfo.getIsVip(), vipInfo.getLevelName(), vipInfo.getSubscriptionType());

            return Result.success(vipInfo);
        } catch (Exception e) {
            log.error("获取用户VIP信息异常: userId={}", userId, e);
            return Result.failed("获取VIP信息失败");
        }
    }

    /**
     * 获取订阅类型的中文文本
     */
    private String getSubscriptionTypeText(String subscriptionType) {
        if (subscriptionType == null) {
            return "";
        }

        switch (subscriptionType) {
            case "WEEKLY":
                return "周卡会员";
            case "MONTHLY":
                return "月卡会员";
            case "QUARTERLY":
                return "季卡会员";
            case "YEARLY":
                return "年卡会员";
            case "TEMP":
                return "临时会员";
            case "SINGLE":
                return "单次会员";
            default:
                return "VIP会员";
        }
    }
}